<template>
  <div class="q-col-gutter-md q-mt-xl">
    <div class="col-12">
      <q-card class="module-card">
        <q-card-section class="q-pa-md">
          <div class="row items-center q-gutter-md">
            <div class="col-auto">
              <q-icon name="music_note" size="30px" class="text-primary" />
            </div>
            <div class="col-auto">
              <div class="text-h6">{{ currentSong.title || '未播放' }}</div>
              <div class="text-caption text-grey-7">
                {{ currentSong.artist || '选择一首歌曲开始播放' }}
              </div>
            </div>
            <div class="col" style="width: 60%; min-width: 200px">
              <div class="row">
                <q-linear-progress
                  :value="playProgress"
                  color="primary"
                  class="col"
                  stripe
                  rounded
                  size="20px"
                  style="width: 100%; cursor: pointer"
                  @click="handleProgressClick"
                />
              </div>
              <div class="row">
                <div class="col-auto text-caption" style="width: 20px">
                  {{ formatTime(currentTime) }}
                </div>
                <q-space />
                <div
                  class="col-auto text-caption text-right"
                  style="width: 30px; padding-right: 20px"
                >
                  {{ formatTime(totalTime) }}
                </div>
              </div>
            </div>
            <div class="col-auto">
              <q-btn round :icon="isPlaying ? 'pause' : 'play_arrow'" @click="togglePlay" />
            </div>
          </div>
        </q-card-section>
        <q-inner-loading :showing="isLoading">
          <q-spinner-ios
            class="absolute-top"
            style="top: 20px; left: 20px"
            color="primary"
            size="20px"
          />
        </q-inner-loading>
      </q-card>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { api } from 'boot/axios'
import { useQuasar } from 'quasar'

const $q = useQuasar()
const emit = defineEmits(['update-history', 'update-duration', 'update-song'])

const props = defineProps({
  currentSong: {
    type: Object,
    required: true,
  },
  songHistory: {
    type: Array,
    default: () => [],
  },
  isClicked: {
    type: Boolean,
    default: false,
  },
})

const audioElement = ref(new Audio())
const currentSong = ref(props.currentSong)
const isPlaying = ref(false)
const currentTime = ref(0)
const totalTime = ref(currentSong.value.duration)
const playProgress = computed(() => currentTime.value / totalTime.value)
const clickedStatus = ref(false)
const isLoading = ref(false)

const GetUserId = () => {
  const userInfo = localStorage.getItem('userInfo') || ''
  try {
    const userInfoJson = JSON.parse(userInfo)
    return userInfoJson.id
  } catch (e) {
    console.error(e)
    return ''
  }
}

const GetMusicUrl = async (path) => {
  try {
    isLoading.value = true
    const res = await api.get(
      '/api/v1/music_json_service?CloudPath=' + `cloud/${GetUserId()}/${path}`,
      {
        headers: {
          ApiKey: btoa(
            `${localStorage.getItem('token') || ''}` +
              '$$' +
              `${localStorage.getItem('email') || ''}`,
          ),
        },
      },
    )
    emit('update-history', res.data.config)
    return res.data.music
  } catch (ex) {
    console.log(ex)
    // if response has exists "message or error". use $q.Notify to show the message/error in top
    if (ex.response?.data?.message) {
      $q.notify({
        message: '获取网盘临时链接失败：' + ex.response.data.message,
        color: 'negative',
        position: 'top',
      })
    }
    if (ex.response?.data?.error) {
      $q.notify({
        message: '获取网盘临时链接失败：' + ex.response.data.error,
        color: 'negative',
        position: 'top',
      })
    }
  } finally {
    isLoading.value = false
  }
  return ''
}
const isReturn = ref(false)
watch(
  () => props.currentSong,
  async (newSong, oldValue) => {
    if (isReturn.value) {
      isReturn.value = false
      return
    }
    currentSong.value = newSong
    if (!newSong.url.includes('http')) {
      const awsUrl = await GetMusicUrl(newSong.url)
      if (!awsUrl) {
        emit('update-song', oldValue)
        isReturn.value = true
        $q.notify({
          message: '获取歌曲失败，已恢复上一首歌',
          color: 'negative',
          position: 'top',
        })
        return
      }
      audioElement.value.src = awsUrl
    } else {
      audioElement.value.src = newSong.url
    }
    console.log(props.isClicked)
    if (clickedStatus.value) {
      audioElement.value.play()
      isPlaying.value = true
    }
  },
  { deep: true },
)

watch(
  () => props.isClicked,
  () => {
    clickedStatus.value = true
    console.log('可以自动播放了')
  },
)

const togglePlay = () => {
  if (!props.currentSong.url) {
    return
  }
  isPlaying.value = !isPlaying.value
  if (isPlaying.value) {
    audioElement.value.play()
  } else {
    audioElement.value.pause()
  }
}

const formatTime = (seconds) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`
}
const handleProgressClick = (e) => {
  const rect = e.target.getBoundingClientRect()
  const percentage = (e.clientX - rect.left) / rect.width
  currentTime.value = Math.round(totalTime.value * percentage)
  audioElement.value.currentTime = currentTime.value
}

onMounted(() => {
  audioElement.value.src = currentSong.value.url

  // 音频元数据加载
  audioElement.value.addEventListener('loadedmetadata', () => {
    totalTime.value = audioElement.value.duration
    currentSong.value.duration = totalTime.value
    emit('update-duration', {
      // 新增emit
      url: currentSong.value.url,
      duration: totalTime.value,
    })
  })

  // 时间更新监听
  audioElement.value.addEventListener('timeupdate', () => {
    currentTime.value = audioElement.value.currentTime
  })

  // 播放结束处理
  audioElement.value.addEventListener('ended', () => {
    isPlaying.value = false
  })

  audioElement.value.addEventListener('error', () => {
    isPlaying.value = false
  })
})

onUnmounted(() => {
  audioElement.value.pause()
  audioElement.value.removeAttribute('src')
})
</script>

<style scoped>
.module-card {
  transition: transform 0.3s;
  border-radius: 12px;
  height: 100%;
}
</style>
